package com.gxa.medical.service.impl;

import com.gxa.medical.exception.BusinessException;
import com.gxa.medical.exception.ExceptionCode;
import com.gxa.medical.mapper.UserMapper;
import com.gxa.medical.pojo.User;
import com.gxa.medical.service.UserService;
import com.gxa.medical.util.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.Map;

@Service
@Transactional(rollbackFor = {Throwable.class})
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Override
    public Integer insertUser(User user) throws Exception {
        //根据手机号查询数据库,如果该手机号存在则抛出异常,如果不存在执行插入操作
        List<User> users = userMapper.selectIdByPhone(user.getPhone());
        user.setPwd(MD5Util.encode(user.getPwd()));
        if (users.size() > 0) {
            throw new BusinessException(ExceptionCode.DUPLICATE_PHONE);
        }
        return userMapper.insertUser(user);
    }

    @Override
    public List<User> selectIdByPhone(String phone) {
        return userMapper.selectIdByPhone(phone);
    }

    @Override
    public List<User> loginUser(User user) throws Exception {
        user.setPwd(MD5Util.encode(user.getPwd()));
        List<User> users = userMapper.loginUser(user);
        if (users.size() > 0) {
            return users;
        }
        throw new BusinessException(ExceptionCode.LOGIN_FAILED);
    }

    @Override
    public Integer updatePwd(User user) throws Exception {
        user.setPwd(MD5Util.encode(user.getPwd()));
        Integer integer = userMapper.updatePwd(user);
        if(integer>0){
            return integer;
        }
       throw new BusinessException(ExceptionCode.UPDATE_USER_FAILED);
    }

    @Override
    public Integer updateMessage(User user) throws Exception {
        Integer integer = userMapper.updateMessage(user);
        if(integer>0){
            return integer;
        }
        throw new BusinessException(ExceptionCode.UPDATE_USER_FAILED);
    }

    @Override
    public Integer updateInformation(Map map)throws Exception {
        Integer integer = userMapper.updateInformation(map);
        if(integer>0){
            return integer;
        }
        throw new BusinessException(ExceptionCode.UPDATE_USER_FAILED);
    }

    @Override
    public Integer updateMany(Integer money, String phone)throws Exception {
        Integer integer = userMapper.updateMany(money,phone);
        if(integer>0){
            return integer;
        }
        throw new BusinessException(ExceptionCode.UPDATE_USER_FAILED);
    }

    @Override
    public User selectMany(String phone) {
        return userMapper.selectMany(phone);
    }
}
